#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __future__ import division, unicode_literals

import os
import math
from django.shortcuts import render, redirect
from django.contrib import messages
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from business import models
from business import forms
from manager import mytool
from django.conf import settings


@login_required(login_url='/login/')
def list_customer(request, number=1):
    """ 显示客户信息列表 """
    username = request.user.username
    list_section = mytool.list_section(number)

    customers = models.CustomerModel.objects.all().order_by('-mod_date')

    all_pages = int(math.ceil(len(customers) / 50))
    columns = list(range(1, all_pages + 1))
    active_page = int(number)
    prev_page = active_page - 1 if (active_page - 1) >= 1 else active_page
    next_page = active_page + 1 if (active_page + 1) <= all_pages\
        else active_page

    customers = customers[list_section[0]: list_section[1]]

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/customer/list_customer.html',
                  request_context)


@login_required(login_url='/login/')
def add_customer(request):
    """ 新增客户信息 """
    username = request.user.username

    if request.method == 'POST':
        customer_add_form = forms.CustomerForm(request.POST)
        customer_name = customer_add_form.data['name']
        flag = models.CustomerModel.objects.filter(name=customer_name)

        # 说明该客户名称已经存在
        if flag:
            messages.add_message(request, messages.WARNING,
                                 '该客户名称已经存在')
        # 然后判断客户名称是否有效
        elif not mytool.validate_customer_name(customer_name):
            messages.add_message(request, messages.WARNING,
                                 '客户名称不能包含特殊字符')
        # 最后判断其他项是否正确
        elif customer_add_form.is_valid():

            customer = customer_add_form.save(commit=False)
            customer.creator = username
            customer.modifier = username
            customer.save()
            show_id = customer.id
            messages.add_message(request, messages.SUCCESS, '添加成功')

            return redirect('/business/show_customer/{0}'.format(show_id))
        else:
            messages.add_message(request, messages.WARNING, '请检查输入的字段')

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'business/customer/add_customer.html',
                  request_context)


@login_required(login_url='/login/')
def mod_customer(request, name):
    """ 修改客户信息 """
    username = request.user.username

    customer = models.CustomerModel.objects.filter(name=name)
    customer = customer[0]
    show_id = customer.id

    if request.method == 'POST':
        customer_mod_form = forms.CustomerForm(request.POST, instance=customer)
        new_name = customer_mod_form.data['name']
        flag = models.CustomerModel.objects.filter(name=new_name)

        if not new_name:
            messages.add_message(request, messages.WARNING,
                                 '客户名称为必填项')

        elif not mytool.validate_customer_name(new_name):
            messages.add_message(request, messages.WARNING,
                                 '客户名称不能包含特殊字符')

        elif flag and new_name != name:
            messages.add_message(request, messages.WARNING,
                                 '该客户名称已经存在')

        elif customer_mod_form.is_valid():
            customer = customer_mod_form.save(commit=False)
            customer.modifier = username
            customer.save()
            messages.add_message(request, messages.SUCCESS, '保存成功')

            return redirect('/business/show_customer/{0}'.format(show_id))
        else:
            messages.add_message(request, messages.WARNING, '请检查输入的字段')

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'business/customer/mod_customer.html', locals())


@login_required(login_url='/login/')
def show_customer(request, _id):
    """ 显示客户信息详情 """
    username = request.user.username

    customer = []
    if _id.isdigit():
        customer = models.CustomerModel.objects.filter(id=_id)

    if not customer:
        customer = models.CustomerModel.objects.filter(name=_id)

    if not customer:
        return redirect('/business')

    customer = customer[0]

    # 获取该用户关联的订单
    orders = models.CircuitOrderModel.objects.filter(customer_id=customer.id)

    # 获取该用户关联的Ticket
    tickets = []
    for order in orders:
        tickets.extend(models.TicketModel.objects.filter(order_id=order.id))

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/customer/show_customer.html',
                  request_context)


@login_required(login_url='/login/')
def search_customer(request):
    """ 显示客户信息详情 """
    username = request.user.username
    customer_id = request.POST['customer']
    customer_id = customer_id.strip()
    if not customer_id:
        messages.add_message(request, messages.WARNING,
                             '请输入搜索信息。'
                             '支持输入用户名称关键词 或者 联系人名称关键词 来查询。')
        return redirect('/business')

    customers = []

    # 优先搜索客户名称
    customers = models.CustomerModel.objects.\
        filter(name__icontains=customer_id)

    # 然后搜索联系人
    if not customers:
        customers = models.CustomerModel.objects.\
            filter(contact__icontains=customer_id)

    # 最后都没有搜索到就报错
    if not customers:
        messages.add_message(request, messages.WARNING,
                             '未找到客户信息，请检查输入信息。'
                             '支持输入用户名称关键词 或者 联系人名称关键词 来查询。')
        return redirect('/business')

    customers = customers.order_by('name')
    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/customer/list_search_customer.html',
                  request_context)


@login_required(login_url='/login/')
def del_customer(request):
    """ 删除线路业务订单 """
    username = request.user.username
    customer_id = request.GET['customer_id']
    customer = models.CustomerModel.objects.filter(id=customer_id)

    try:
        customer.delete()
    except Exception:
        messages.add_message(request, messages.WARNING, '删除失败')
    else:
        messages.add_message(request, messages.SUCCESS, '删除成功')

    request_context = RequestContext(request)
    request_context.push(locals())

    # 必须要返回HTTP数据，回调函数才会生效。
    return HttpResponse("操作删除客户信息")


@login_required(login_url='/login/')
def list_circuit_order(request, number=1):
    """ 显示线路业务订单列表 """
    username = request.user.username
    list_section = mytool.list_section(number)
    orders = models.CircuitOrderModel.objects.all().order_by('-mod_date')

    all_pages = int(math.ceil(len(orders) / 50))
    columns = list(range(1, all_pages + 1))
    active_page = int(number)
    prev_page = active_page - 1 if (active_page - 1) >= 1 else active_page
    next_page = active_page + 1 if (active_page + 1) <= all_pages else\
        active_page

    orders = orders[list_section[0]: list_section[1]]

    for order in orders:
        customer = models.CustomerModel.objects.filter(id=order.customer_id)[0]
        _name = customer.name
        order.customer_name = _name

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/circuit_order/list_circuit_order.html',
                  request_context)


@login_required(login_url='/login/')
def add_circuit_order(request, _id):
    """ 新增线路业务订单，参数_id为客户的ID"""
    username = request.user.username
    customer = models.CustomerModel.objects.get(id=_id)
    customer_name = customer.name
    dir_path = os.path.join(settings.MEDIA_ROOT, 'circuit_order', str(customer.id))

    if request.method == 'POST':
        attachment = request.FILES.get('attachment', '')
        order_add_form = forms.CircuitOrderForm(request.POST)
        number = order_add_form.data['number']
        flag = models.CircuitOrderModel.objects.filter(number=number)

        if not number:
            messages.add_message(request, messages.WARNING,
                                 '线路编号为必填项')

        if not mytool.validate_number(number):
            messages.add_message(request, messages.WARNING,
                                 '线路编号只能由数字字母 - 或者 _ 组成')

        elif flag:
            messages.add_message(request, messages.WARNING,
                                 '该线路编号已经存在')

        elif order_add_form.is_valid():
            order = order_add_form.save(commit=False)
            order.creator = username
            order.modifier = username
            if attachment:
                # 将附件写入服务器
                if not os.path.isdir(dir_path):
                    os.makedirs(dir_path)

                file_path = os.path.join(dir_path, attachment.name)
                try:
                    with open(file_path.encode('utf-8'), 'wb') as f:
                        for chunk in attachment.chunks():
                            f.write(chunk)

                except Exception as e:
                    messages.add_message(request, messages.WARNING,
                                         u"附件上传失败，请稍后再试。原因: {0}".format(e))

                order.attachment = attachment.name.encode('utf-8')

            order.customer_id = _id
            order.save()
            show_id = order.id
            messages.add_message(request, messages.SUCCESS, '添加成功')

            return redirect('/business/show_circuit_order/{0}'.format(show_id))
        else:
            messages.add_message(request, messages.WARNING, '请检查输入的字段')

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'business/circuit_order/add_circuit_order.html',
                  request_context)


@login_required(login_url='/login/')
def show_circuit_order(request, _number):
    """ 显示线路业务订单详情 """
    username = request.user.username

    order = []
    if _number.isdigit():
        order = models.CircuitOrderModel.objects.filter(id=_number)

    if not order:
        order = models.CircuitOrderModel.objects.filter(number=_number)

    if not order:
        return redirect('/business/circuit_order')

    order = order[0]
    if order.attachment:
        attachment_name = os.path.\
            basename(order.attachment.name.encode('utf-8'))

    # 获取关联的客户名称
    customer = models.CustomerModel.objects.filter(id=order.customer_id)[0]

    # 获取关联的Ticket
    tickets = models.TicketModel.objects.filter(order_id=order.id)

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/circuit_order/show_circuit_order.html',
                  request_context)


@login_required(login_url='/login/')
def search_circuit_order(request):
    """ 搜索线路业务订单 """
    username = request.user.username
    circuit = request.POST['circuit']
    circuit = circuit.strip()
    if not circuit:
        messages.add_message(request, messages.WARNING,
                             '请输入搜索信息。'
                             '支持输入线路编号(不区分大小写) 或者 '
                             '客户名称关键词 来查询。')
        return redirect('/business/circuit_order')

    orders = []

    # 先按照线路编号查找
    _orders = models.CircuitOrderModel.objects.\
        filter(number__icontains=circuit)

    # 然后安装客户名称查找
    if not _orders:
        _orders = models.CustomerModel.objects.\
            filter(name__icontains=circuit)

        for _order in _orders:
            _id = _order.id
            _name = _order.name
            order = models.CircuitOrderModel.objects.\
                filter(customer_id=_id)
            if order:
                for o in order:
                    o.customer_name = _name
                    orders.append(o)
    else:
        for o in _orders:
            _customer = models.CustomerModel.objects.\
                filter(id=o.customer_id)[0]
            o.customer_name = _customer.name
            orders.append(o)

    if not orders:
        messages.add_message(request, messages.WARNING,
                             '未找订单信息，请检查输入信息。'
                             '支持输入线路编号(不区分大小写) 或者 '
                             '客户名称关键词 来查询。')
        return redirect('/business/circuit_order')

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request,
                  'business/circuit_order/list_search_circuit_order.html',
                  request_context)


@login_required(login_url='/login/')
def mod_circuit_order(request, _id):
    """ 修改线路业务订单 """
    username = request.user.username

    order = models.CircuitOrderModel.objects.filter(id=_id)
    order = order[0]
    number = order.number

    # 上传附件是需要
    dir_path = os.path.join(settings.MEDIA_ROOT, 'circuit_order', str(order.customer.id))

    if request.method == 'POST':
        attachment = request.FILES.get('attachment', '')
        order_mod_form = forms.CircuitOrderForm(request.POST, instance=order)
        new_number = order_mod_form.data['number']
        flag = models.CircuitOrderModel.objects.filter(number=new_number)

        if not new_number:
            messages.add_message(request, messages.WARNING,
                                 '线路编号为必填项')

        if not mytool.validate_number(new_number):
            messages.add_message(request, messages.WARNING,
                                 '线路编号只能由数字字母 - 或者 _ 组成')

        elif flag and new_number != number:
            messages.add_message(request, messages.WARNING,
                                 '该线路编号已经存在')

        elif order_mod_form.is_valid():
            order = order_mod_form.save(commit=False)

            if attachment:
                # 将附件保存到服务器
                if not os.path.isdir(dir_path):
                    os.makedirs(dir_path)

                file_path = os.path.join(dir_path, attachment.name)
                try:
                    with open(file_path.encode('utf-8'), 'wb') as f:
                        for chunk in attachment.chunks():
                            f.write(chunk)

                except Exception as e:
                    messages.add_message(request, messages.WARNING,
                                         u"附件上传失败，请稍后再试。原因: {0}".format(e))

                order.attachment = attachment.name.encode('utf-8')

            order.modifier = username
            order.save()
            messages.add_message(request, messages.SUCCESS, '保存成功')

            return redirect('/business/show_circuit_order/{0}'.format(_id))
        else:
            messages.add_message(request, messages.WARNING, '请检查输入的字段')

    if order.attachment:
        attachment_name = os.path.\
            basename(order.attachment.name.encode('utf-8'))

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'business/circuit_order/mod_circuit_order.html',
                  locals())


@login_required(login_url='/login/')
def del_circuit_order(request):
    """ 删除线路业务订单 """
    username = request.user.username
    order_id = request.GET['circuit_order_id']
    order = models.CircuitOrderModel.objects.filter(id=order_id)

    try:
        order.delete()
    except Exception:
        messages.add_message(request, messages.WARNING, '删除失败')
    else:
        messages.add_message(request, messages.SUCCESS, '删除成功')

    request_context = RequestContext(request)
    request_context.push(locals())

    # 必须要返回HTTP数据，回调函数才会生效。
    return HttpResponse("操作删除线路业务订单")


@login_required(login_url='/login/')
def list_ticket(request, number=1):
    """ 显示Ticket列表 """
    username = request.user.username
    list_section = mytool.list_section(number)
    tickets = models.TicketModel.objects.all().order_by('-mod_date')

    all_pages = int(math.ceil(len(tickets) / 50))
    columns = list(range(1, all_pages + 1))
    active_page = int(number)
    prev_page = active_page - 1 if (active_page - 1) >= 1 else active_page
    next_page = active_page + 1 if (active_page + 1) <= all_pages else\
        active_page

    tickets = tickets[list_section[0]: list_section[1]]

    for ticket in tickets:
        order = models.CircuitOrderModel.objects.filter(id=ticket.order_id)[0]
        customer = models.CustomerModel.objects.filter(id=order.customer_id)[0]

        ticket.customer_name = customer.name
        ticket.order_number = order.number

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/ticket/list_ticket.html', request_context)


@login_required(login_url='/login/')
def show_ticket(request, _id):
    """ 显示Ticket详情 """
    username = request.user.username

    ticket = []
    if _id.isdigit():
        ticket = models.TicketModel.objects.filter(id=_id)

    if not ticket:
        return redirect('/business/ticket')

    ticket = ticket[0]

    # 获取关联的订单和客户名称
    order = models.CircuitOrderModel.objects.filter(id=ticket.order_id)[0]
    customer = models.CustomerModel.objects.filter(id=order.customer_id)[0]
    ticket.customer_name = customer.name
    ticket.order_number = order.number

    # 获取该用户关联的Ticket
    ticket_messages = models.TicketMessageModel.objects.\
        filter(ticket_id=ticket.id)

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/ticket/show_ticket.html', request_context)


@login_required(login_url='/login/')
def add_ticket(request, _id):
    """ 新增Ticket, 参数_id为订单的ID"""
    username = request.user.username
    order_id = _id
    customer_name = models.CircuitOrderModel.objects.filter(id=_id).\
        values('customer__name')[0]
    customer_name = customer_name.get('customer__name', '')

    if request.method == 'POST':
        ticket_add_form = forms.TicketForm(request.POST)
        if ticket_add_form.is_valid():
            ticket = ticket_add_form.save(commit=False)
            ticket.creator = username
            ticket.modifier = username
            ticket.order_id = _id
            ticket.save()
            show_id = ticket.id
            messages.add_message(request, messages.SUCCESS, '添加成功')

            return redirect('/business/show_ticket/{0}'.format(show_id))
        else:
            messages.add_message(request, messages.WARNING, '请检查输入的字段')

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/ticket/add_ticket.html', request_context)


@login_required(login_url='/login/')
def mod_ticket(request, _id):
    """ 修改Ticket """
    username = request.user.username

    ticket = models.TicketModel.objects.filter(id=_id)
    ticket = ticket[0]

    if request.method == 'POST':
        ticket_mod_form = forms.TicketForm(request.POST, instance=ticket)
        if ticket_mod_form.is_valid():
            ticket = ticket_mod_form.save(commit=False)
            ticket.modifier = username
            ticket.save()
            messages.add_message(request, messages.SUCCESS, '保存成功')

            return redirect('/business/show_ticket/{0}'.format(_id))
        else:
            messages.add_message(request, messages.WARNING, '请检查输入的字段')

    request_context = RequestContext(request)
    request_context.push(locals())
    return render(request, 'business/ticket/mod_ticket.html', locals())


@login_required(login_url='/login/')
def del_ticket(request):
    """ 删除Ticket """
    username = request.user.username
    ticket_id = request.GET['ticket_id']
    ticket = models.TicketModel.objects.filter(id=ticket_id)

    try:
        ticket.delete()
    except Exception:
        messages.add_message(request, messages.WARNING, '删除失败')
    else:
        messages.add_message(request, messages.SUCCESS, '删除成功')

    request_context = RequestContext(request)
    request_context.push(locals())

    # 必须要返回HTTP数据，回调函数才会生效。
    return HttpResponse("操作删除Ticket")


@login_required(login_url='/login/')
def add_ticket_message(request, _id):
    """ 新增TicketMessage, 参数_id为Ticket的ID"""
    username = request.user.username
    ticket_id = _id

    if request.method == 'POST':
        ticket_message_add_form = forms.TicketMessageForm(request.POST)
        if ticket_message_add_form.is_valid():
            ticket_message = ticket_message_add_form.save(commit=False)
            ticket_message.creator = username
            ticket_message.modifier = username
            ticket_message.ticket_id = _id
            ticket_message.save()

            messages.add_message(request, messages.SUCCESS, '添加成功')
            return redirect('/business/show_ticket/{0}'.format(_id))
        else:
            messages.add_message(request, messages.WARNING, '请输入处理记录内容')
            return redirect('/business/show_ticket/{0}'.format(_id))

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/other/add_ticket_message_modal.html',
                  request_context)


@login_required(login_url='/login/')
def mod_ticket_message(request, _id):
    """ 修改TicketMessage """
    username = request.user.username

    ticket_message = models.TicketMessageModel.objects.filter(id=_id)
    ticket_message = ticket_message[0]
    show_id = ticket_message.ticket_id

    if request.method == 'POST':
        ticket_message_mod_form = \
            forms.TicketMessageForm(request.POST, instance=ticket_message)

        if ticket_message_mod_form.is_valid():
            ticket_message = ticket_message_mod_form.save(commit=False)
            ticket_message.modifier = username
            ticket_message.save()

            messages.add_message(request, messages.SUCCESS, '保存成功')
            return redirect('/business/show_ticket/{0}'.format(show_id))
        else:
            messages.add_message(request, messages.WARNING, '请输入处理记录内容')
            return redirect('/business/show_ticket/{0}'.format(show_id))

    request_context = RequestContext(request)
    request_context.push(locals())

    return render(request, 'business/other/mod_ticket_message_modal.html',
                  request_context)


@login_required(login_url='/login/')
def del_ticket_message(request):
    """ 删除TicketMessage """
    username = request.user.username
    ticket_message_id = request.GET['ticket_message_id']
    ticket_message = models.TicketMessageModel.objects.\
        filter(id=ticket_message_id)
    ticket_message = ticket_message[0]
    show_id = ticket_message.ticket_id

    try:
        ticket_message.delete()
    except Exception:
        messages.add_message(request, messages.WARNING, '删除失败')
    else:
        messages.add_message(request, messages.SUCCESS, '删除成功')

    request_context = RequestContext(request)
    request_context.push(locals())

    # 必须要返回HTTP数据，回调函数才会生效。
    return HttpResponse("操作删除Ticket处理记录")
